package com.example.spider.utils;

import org.apache.commons.io.FileUtils;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.config.RequestConfig;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.ParseException;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.util.Timeout;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class HttpsUtils {

    //连接池
    private PoolingHttpClientConnectionManager manager;

    public HttpsUtils(){
        this.manager = new PoolingHttpClientConnectionManager();
        //最大连接数
        this.manager.setMaxTotal(100);
        //最大主机连接数
        this.manager.setDefaultMaxPerRoute(10);
    }

    //下载文件为字符串
    public String downloadHtml(String url) {
        //使用连接池模拟浏览器
        CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(this.manager).build();
        //创建请求
        HttpGet httpGet = new HttpGet(url);
        //配置请求参数
        RequestConfig config = setConfig();
        //设置请求参数
        httpGet.setConfig(config);

        //发送请求，获得结果
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpGet);
            //解析数据
            if (response.getCode() == 200 && response.getEntity()!=null){
                HttpEntity httpEntity = response.getEntity();
                return EntityUtils.toString(httpEntity, "utf8");
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }finally {
            if (response!=null) {
                try {
                    response.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
        return null;
    }

    //下载图片
    public String downloadImage(String url,String filePath) {
        //使用连接池模拟浏览器
        CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(this.manager).build();
        //创建请求
        HttpGet httpGet = new HttpGet(url);
        //配置请求参数
        RequestConfig config = setConfig();
        //设置请求参数
        httpGet.setConfig(config);

        //发送请求，获得结果
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpGet);
            //解析数据
            if (response.getCode() == 200 && response.getEntity()!=null){
                //下载图片
                //获取图片后缀
                String suffix = url.substring(url.lastIndexOf("."));
                //重命名图片
                String imageName = GenerateUUID.getId() + suffix;
                //获取响应体
                HttpEntity httpEntity = response.getEntity();
                //创建流
                FileOutputStream fileOutputStream = new FileOutputStream(new File(filePath + imageName));
                //保存
                httpEntity.writeTo(fileOutputStream);

                return imageName;
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            if (response!=null) {
                try {
                    response.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
        return null;
    }

    public RequestConfig setConfig(){
        return RequestConfig.custom().setConnectTimeout(Timeout.ofSeconds(1))//设置连接最大超时时间
                .setConnectionRequestTimeout(Timeout.ofSeconds(1))//获取连接的最大时间
                .setResponseTimeout(Timeout.ofSeconds(10))//数据最大传输时间
                .build();
    }
}
